package com.tanhua.server.interceptor;

import com.tan.model.domain.User;
import com.tanhua.commons.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      String token =  request.getHeader("Authorization");
      Boolean flag =  JwtUtils.isValidToken(token);
//      if(!flag){
//          response.setStatus(401);
//          return false;
//      }
      User user = new User();
  Claims claims = JwtUtils.verify(token);
     Integer id = (Integer) claims.get("id");
     String mobile = (String) claims.get("mobile");
     user.setId(id.longValue());
     user.setMobile(mobile);
     Userthread.setUser(user);
      return true;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        Userthread.removeUser();
    }
}
